define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxWorkarea";

    var fxWorkareaFormHtml = sysPath + "/views/fxWorkareaForm.html";
    var getFxWorkareaController = function () {
        return getServer() + "/fxWorkareas";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        createFxWorkareaGrid();
    };


    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createFxWorkareaGrid();
        });
        $("#btnReset").click(function () {
            $("#workspaceCondition").val("");
            $("#magnitudeCondition").val("");
        });
    };
    var createFxWorkareaGrid = function () {
        $("#fxWorkareaGrid").datagrid({
            url: getFxWorkareaController() + "/queryFxWorkareas",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'workspace',
                    title: '工作区名称',
                    width: '16%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxWorkarea(\'' + rowData.id + '\');"> ' + rowData.workspace + ' </a> '
                    }
                },
                {
                    field: 'coverArea',
                    title: '覆盖市县',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'magnitude',
                    title: '震级',
                    width: '16%',
                    align: 'center',
                },
                {
                    field: 'estimateArea',
                    title: '评估区面积（km2）',
                    width: '16%',
                    align: 'center',
                },
                {
                    field: 'population',
                    title: '震级评估区人口（万）',
                    width: '16%',
                    align: 'center',
                },
                {
                    field: 'gdp',
                    title: 'GDP（亿元）',
                    width: '15%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addFxWorkarea();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    downloadTemplate();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteFxWorkarea();
                }
            }],
            queryParams: {
                workspace: $("#workspaceCondition").val(),
                magnitude: $("#magnitudeCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#fxWorkareaForm").validate({
            rules: {
                workspace: {
                    required: true,
                },
                coverArea: {
                    required: true,
                },
                magnitude: {
                    required: true,
                },
                year: {
                    required: true,
                },
                estimateArea: {
                    required: true,
                },
                population: {
                    required: true,
                },
                gdp: {
                    required: true,
                },
            },
            messages: {
                workspace: {
                    required: "工作区名称不允许为空!",
                },
                coverArea: {
                    required: "覆盖市县不允许为空!",
                },
                magnitude: {
                    required: "震级不允许为空!",
                },
                year: {
                    required: "年份不允许为空!",
                },
                estimateArea: {
                    required: "评估区面积（km2）不允许为空!",
                },
                population: {
                    required: "震级评估区人口（万）不允许为空!",
                },
                gdp: {
                    required: "GDP（亿元）不允许为空!",
                },
            }
        });
    };
    var getFxWorkarea = function (id) {
        $.ajax({
            url: getFxWorkareaController() + "/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("fxWorkareaForm", data);
            }
        });
    };
    /**
     * 添加
     */
    var addFxWorkarea = function () {
        var slidebar = Util.slidebar({
            url: fxWorkareaFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxWorkareaForm").valid()) {
                        var data = Tool.serialize("fxWorkareaForm");
                        $.ajax({
                            url: getFxWorkareaController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxWorkareaGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    /**
     * 下载模板
     */
    var downloadTemplate = function () {
        window.location.href = getServer() + "/excel/工作区数据模板.xlsx";
    };
    /**
     * 导入
     */
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/工作区数据模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });
        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxWorkareaController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                    createFxWorkareaGrid();
                }
            });
        });
    };

    /**
     * 导出
     */
    var exportForm = function () {
        let workspace = $("#workspaceCondition").val();
        let magnitude = $("#magnitudeCondition").val();
        window.location.href = getFxWorkareaController() + "/export?workspace=" + workspace + "&magnitude=" + magnitude;
    };

    window._editFxWorkarea = function (fxWorkareaId) {
        var slidebar = Util.slidebar({
            url: fxWorkareaFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                getFxWorkarea(fxWorkareaId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxWorkareaForm").valid()) {
                        var data = Tool.serialize("fxWorkareaForm");
                        $.ajax({
                            url: getFxWorkareaController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxWorkareaGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxWorkarea = function () {
        var rows = $("#fxWorkareaGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxWorkareaController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxWorkareaGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
